package lojaVirtual.manterCadastro.dao;

import javax.persistence.EntityManager;

import java.io.Serializable;
import java.util.List;

import lojaVirtual.manterCadastro.pojo.Entidade;
import lojaVirtual.uteis.EntityManagerProvider;

@SuppressWarnings("serial")
public class GenericDao<E extends Entidade> implements Serializable{


	private final EntityManager em;
	private Class<E> classe;


	/**
	 * 
	 * @param classe
	 */
	public GenericDao(Class<E> classe) {
		this.em = EntityManagerProvider.getEntityManagerFactory();
		this.classe = classe;
	}

	/**
	 * 
	 * @param classe
	 */
	public void setClasse(Class<E> classe){
		
		this.classe = classe;
	}
	

	/**
	 * 
	 * @param e
	 */
	public void save(E e) {
		
		this.em.getTransaction().begin();
		this.em.persist(e);
		this.em.getTransaction().commit();
	}

	/**
	 * 
	 * @param e
	 */
	public void delete(E e) {
		
		this.em.getTransaction().begin();
		this.em.remove(e);
		this.em.getTransaction().commit();
		
	}
	
	/**
	 * 
	 * @param id
	 * @return
	 */
	public E find(int id) {
		
		this.em.getTransaction().begin();
		E e = this.em.getReference(classe, id);
		this.em.getTransaction().commit();
		
		return e;
	}
	
	public List<E> findByName(String column, String name){
		
		this.em.getTransaction().begin();
		@SuppressWarnings("unchecked")
		List<E> e = this.em.createQuery("from " + classe.getName() + " where " + column + " = '" + name + "'").getResultList();
		this.em.getTransaction().commit();
		
		return e;
	}
	
	

	/**
	 * 
	 * @return
	 */
/*	@SuppressWarnings("unchecked")
	public List<E> list() {
		
		this.em.getTransaction().begin();
		List<E> list = em.createQuery("from " + classe.getName()).getResultList();
		this.em.getTransaction().commit();
		return list;
	}*/

	
	/**
	 * Retorna lista ordenada.
	 * @return list
	 */
	@SuppressWarnings("unchecked")
	public List<E> list( String ordem ) {
		
		this.em.getTransaction().begin();
		List<E> list = em.createQuery("from " + classe.getName() + " order by " + ordem).getResultList();
		this.em.getTransaction().commit();
		return list;
	}

	
	/**
	 * Retorna lista ordenada.
	 * @return list
	 */
	@SuppressWarnings("unchecked")
	public List<E> list( String ordem, String where ) {
		
		this.em.getTransaction().begin();
		List<E> list = em.createQuery("from " + classe.getName() + " where " + where + " order by " + ordem).getResultList();
		this.em.getTransaction().commit();
		return list;
	}
	
	/**
	 * 
	 * @param ordem
	 * @param where
	 * @param join
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<E> list( String ordem, String where, String join ) {
		
		this.em.getTransaction().begin();
		List<E> list = em.createQuery("from " + classe.getName() + " " + join +" where " + where + " order by " + ordem).getResultList();
		this.em.getTransaction().commit();
		return list;
	}
}
